/*
 * XbLiteReader.cpp
 *
 *  Created on: Dec 19, 2009
 *      Author: evaleto
 */

#include "XbLiteReader.h"

XbLiteReader::XbLiteReader() {
	_serial=&Serial;
	clear();
}

XbLiteReader::~XbLiteReader() {
	if (data!=NULL){
		free(data);
		data=NULL;
	}
}


void XbLiteReader::begin(long baud) {
	_serial->begin(baud);
}

void XbLiteReader::setSerial(HardwareSerial &serial) {
	_serial = &serial;
}
uint8_t  XbLiteReader::readbyte(){
  while(!_serial->available());
  return _serial->read();
}

void XbLiteReader::read(){
		if (!_serial->available()){
			error=NO_DATA;
			return;
		}
		clear();

		uint8_t b=readbyte();
		if (b != START_IOPACKET){
			//TODO ERROR
//			Serial.print(b,HEX);
			error= (UNEXPECTED_START_IOPACKET);
			return;
		}
		uint8_t lmsb = readbyte();
		lmsb = 0x20 ^ lmsb;

		uint8_t llsb = readbyte();
		llsb = 0x20 ^ llsb;

		uint8_t len = (llsb + (lmsb<< 8)) + 1;

		data=(uint8_t*)malloc(len);
		if(data==NULL){
			//TODO ERROR
			error= (BAD_ALLOC);
			return;
		}
		// read the xb frame
		for (uint8_t i=0;i<len;i++){
			data[i]=readbyte();
		}
		decode(data);
		free(data);
		data=(uint8_t*)NULL;
}
void XbLiteReader::decode(uint8_t data[]) {
	app_id = data[0];
	if(app_id != SERIES1_IOPACKET){
		error= (UNEXPECTED_APPID);
		return;
	}
#ifdef CONFIG_WITH_FULLXBEE
	uint8_t addrMSB = data[1];
	uint8_t addrLSB = data[2];
	address_16 = (addrMSB << 8) + addrLSB;

	rssi = data[3];
	address_broadcast = ((data[4] >> 1) & 0x01) == 1;
	pan_broadcast = ((data[4] >> 2) & 0x01) == 1;

	total_samples = data[5];
	channel_indicator_high = data[6];
	channel_indicator_low = data[7];

	local_checksum = uint16_t(app_id) + addrMSB + addrLSB + rssi + data[4] + total_samples + channel_indicator_high + channel_indicator_low;
#endif
	error=0;

}

void XbLiteReader::clear(){
	app_id=	address_16 = rssi =0;
	total_samples = channel_indicator_high = channel_indicator_low = local_checksum = 0;
	address_broadcast = pan_broadcast=false;
	error=NULL_STATE;
}
